Ext.define('Inbox.view.inbox.FolderTab', {
	extend : 'Ext.tab.Panel',
	alias : 'widget.folderTab',
	requires : [ 'Inbox.view.inbox.FolderDetail',
			'Inbox.view.inbox.FolderPost', 'Inbox.view.inbox.FolderGrid' ],
	minTabWidth : 150,
	maxTabWidth : 250,
	border : false,

	initComponent : function() {
		this.tabBar = {
			border : true
		};

		this.callParent();
	},

	showFolder : function(title, url) {
		var active = this.items.first();
		if (!active) {
			console.log('Folder selected: ' + title);
			active = this.add({
				xtype : 'folderDetail',
				title : title,
				url : url,
				closable : false,
				listeners : {
					scope : this,
					opentab : this.onTabOpen,
					rowdblclick : this.onRowDblClick
				}
			});
		} else {
			active.loadFolder(url);
			active.tab.setText(title);
		}
		this.setActiveTab(active);
	},

	onTabOpen : function(folder, rec) {
		var items = [], item, title;
		if (Ext.isArray(rec)) {
			Ext.each(rec, function(rec) {
				title = rec.get('title');
				if (!this.getTabByTitle(title)) {
					items.push({
						inTab : true,
						xtype : 'folderPost',
						title : title,
						closable : true,
						data : rec.data,
						active : rec
					});
				}
			}, this);
			this.add(items);
		} else {
			title = rec.get('title');
			item = this.getTabByTitle(title);
			if (!item) {
				item = this.add({
					inTab : true,
					xtype : 'folderPost',
					title : title,
					closable : true,
					data : rec.data,
					active : rec
				});
			}
			this.setActiveTab(item);
		}
	},

	getTabByTitle : function(title) {
		var index = this.items.findIndex('title', title);
		return (index < 0) ? null : this.items.getAt(index);
	},

	onRowDblClick : function(info, rec) {
		this.onTabOpen(null, rec);
	}
});